package com.flycms.modules.picture.controller;

import com.flycms.common.controller.BaseController;
import com.flycms.modules.company.entity.Company;
import com.flycms.modules.company.service.CompanyService;
import com.flycms.modules.picture.entity.Picture;
import com.flycms.modules.picture.service.PictureService;
import com.flycms.modules.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author 孙开飞
 * @version 1.0 <br/>
 * @Description: ${Description}
 * @email 79678111@qq.com
 * @Date: 16:40 2019/11/4
 */
@Controller
public class PictureMemberController extends BaseController {
    @Autowired
    private PictureService pictureService;
    @Autowired
    private CompanyService companyService;

    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////

    /*
     * KindEditor编辑器上传图片接口
     */
    @ResponseBody
    @RequestMapping("/member/kindEditorUpload")
    public Map<String, Object> kindEditorFileUpload(@RequestParam("imgFile") MultipartFile file)throws Exception, IOException {
        Map<String, Object> map = new HashMap<>();
        Company company=companyService.findCompanyByUser(ShiroUtils.getLoginUser().getId());
        if (company ==null){
            map.put("errno", 1);
            map.put("message", "您不是企业用户，没有上传权限");
            return map;
        }
        if (!file.isEmpty()) {
            String proName = siteConstants.getUploadLoaderPath();
            String path = pictureService.getImgPath();
            String uploadContentType = file.getContentType();
            String expandedName = "";
            if ("image/jpeg".equals(uploadContentType)
                    || uploadContentType.equals("image/jpeg")) {
                // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
                expandedName = ".jpg";
            } else if ("image/png".equals(uploadContentType) || "image/x-png".equals(uploadContentType)) {
                // IE6上传的png图片的headimageContentType是"image/x-png"
                expandedName = ".png";
            } else if ("image/gif".equals(uploadContentType)) {
                expandedName = ".gif";
            } else if ("image/bmp".equals(uploadContentType)) {
                expandedName = ".bmp";
            } else {
                map.put("errno", 1);
                map.put("message", "文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）");
                return map;
            }
            if (file.getSize() > 1024 * 1024 * 2) {
                map.put("errno", 1);
                map.put("message", "文件大小不得大于2M");
                return map;
            }

            File dirFile = new File(proName+path);
            //判断文件父目录是否存在
            if(!dirFile.exists() || !dirFile.isDirectory()) {
                dirFile.mkdirs();
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            //图片指纹MD5为文件名
            String fileName = pictureService.md5HashCode32(inputStream);

            Picture imgService=pictureService.findPictureBySignature(company.getId(),fileName);
            if(imgService==null){
                FileOutputStream out = new FileOutputStream(proName+path + fileName + expandedName);
                out.write(file.getBytes());
                out.flush();
                out.close();

                //图片信息写入数据库
                Picture picture = new Picture();
                picture.setSignature(fileName);
                picture.setImgUrl(path + fileName + expandedName);
                picture.setCompanyId(company.getId());
                picture.setImgName(file.getOriginalFilename());
                boolean data=pictureService.addUserPicture(picture);
                if(!data){
                    map.put("errno", 1);
                    map.put("message", "图片保存数据库时出错");
                    return map;
                }

                int port=request.getServerPort();
                String portstr="";
                if(port>0 && port!=80){
                    portstr+=":"+port;
                }
                map.put("url", "http://"+ request.getServerName() + portstr + path + fileName+ expandedName);
            }else{
                map.put("url", imgService.getImgUrl());
            }
            map.put("error", 0);

        } else {
            map.put("error", 1);
            map.put("message", "请选择图片");
        }
        return map;
    }

    /*
     * layui上传图片接口
     */
    @ResponseBody
    @RequestMapping("/member/layuiUpload")
    public Map<String, Object> layuiUploadFileUpload(@RequestParam("file") MultipartFile file)throws Exception, IOException {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Company company=companyService.findCompanyByUser(ShiroUtils.getLoginUser().getId());
        if (company ==null){
            map.put("code", 1);
            map.put("msg", "您不是企业用户，没有上传权限");
            return map;
        }
        if (!file.isEmpty()) {
            String proName = siteConstants.getUploadLoaderPath();
            String path = pictureService.getImgPath();
            String uploadContentType = file.getContentType();
            String expandedName = "";
            if ("image/jpeg".equals(uploadContentType)
                    || uploadContentType.equals("image/jpeg")) {
                // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
                expandedName = ".jpg";
            } else if ("image/png".equals(uploadContentType) || "image/x-png".equals(uploadContentType)) {
                // IE6上传的png图片的headimageContentType是"image/x-png"
                expandedName = ".png";
            } else if ("image/gif".equals(uploadContentType)) {
                expandedName = ".gif";
            } else if ("image/bmp".equals(uploadContentType)) {
                expandedName = ".bmp";
            } else {
                map.put("code", 1);
                map.put("msg", "文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）");
                return map;
            }
            if (file.getSize() > 1024 * 1024 * 2) {
                map.put("code", 1);
                map.put("msg", "文件大小不得大于2M");
                return map;
            }

            File dirFile = new File(proName+path);
            //判断文件父目录是否存在
            if(!dirFile.exists() || !dirFile.isDirectory()) {
                dirFile.mkdirs();
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            //图片指纹MD5为文件名
            String fileName = pictureService.md5HashCode32(inputStream);

            Picture imgService=pictureService.findPictureBySignature(company.getId(),fileName);
            if(imgService==null){
                FileOutputStream out = new FileOutputStream(proName+path + fileName + expandedName);
                out.write(file.getBytes());
                out.flush();
                out.close();

                //图片信息写入数据库
                Picture picture = new Picture();
                picture.setSignature(fileName);
                picture.setImgUrl(path + fileName + expandedName);
                picture.setCompanyId(company.getId());
                picture.setImgName(file.getOriginalFilename());
                boolean dataimg=pictureService.addUserPicture(picture);
                if(!dataimg){
                    map.put("code", 1);
                    map.put("msg", "图片保存数据库时出错");
                    return map;
                }

                int port=request.getServerPort();
                String portstr="";
                if(port>0 && port!=80){
                    portstr+=":"+port;
                }

                data.put("src", path + fileName+ expandedName);
            }else{
                data.put("src",imgService.getImgUrl());
            }
            map.put("code", 0);
            map.put("msg", "上传成功");
            map.put("data", data);
        } else {
            map.put("code", 1);
            map.put("msg", "请选择图片");
        }
        return map;
    }
    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////

    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////



    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////

}
